<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- <link rel="stylesheet" href="../font/iconfont.css"> -->
    <script src="../js/cookie.js"></script>
    <style>
        .createCode {
            user-select: none;
        }

        .right {
            font-size: 12px;
            color: green;
        }

        .error {
            font-size: 12px;
            color: red;
        }
    </style>
</head>

<body>
    <div class="box">
        <p>
            <label for="">用户名:</label>
            <input type="text" class="user">
            <span class="user_span"></span>
        </p>
        <p>
            <label for="">密&emsp;码:</label>
            <input type="text" class="pwd">
            <span class="pwd_span"></span>
        </p>

        <p>
            <input class="btn" type="submit" value="登录">
        </p>
    </div>
</body>

<script>

    var userInp = document.querySelector(".user");
    var userSpan = document.querySelector(".user_span");
    var pwdInp = document.querySelector(".pwd");
    var pwdSpan = document.querySelector(".pwd_span");
    var btn = document.querySelector(".btn");


    btn.onclick = function () {
        // 用户输入的
        var user = userInp.value; // "a123123"
        var pwd = pwdInp.value;

        // 1. 前端传入用户名和密码 
        // 2. 后端接收 -> 对应用户查找是否存在该数据?
        //    a. 不存在 => 未注册  => 失败
        //    b. 存在 => 获取数据 => 对比密码  => 登录成功

        if (user && pwd) {
            var xhr = new XMLHttpRequest();

            xhr.open("post", "../php/login.php", true);

            // FormData
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.send(`user=${user}&pwd=${pwd}`);

            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var result = xhr.responseText;

                    result = JSON.parse(result);

                    console.log(result);

                    var { status, message } = result;
                    if (status) {
                        setCookie("lgc", user, 31 * 24 * 60 * 60)
                        location.href = "index.html";
                    } else {
                        alert(message);
                    }


                }
            }
        }

    }


</script>

</html>